<template>
  <div class="pay-card">
    <h1 class="title">支付订单</h1>
    <el-divider></el-divider>

    <!-- 订单 -->
    <div v-for="(item, index) in store.state.order.orderList"
      style="background: #f6f1ee80; border: 1px solid #92929246; border-radius: 5px; margin-bottom: 30px;">
      <div class="expand-row">
        <!-- 订单详情 -->
        <h1 class="title">订单详情：</h1>

        <!-- 订单内容 -->
        <el-table v-loading="loading" :data="item.orderItemList" :border="true">
          <el-table-column label="商品图片" align="center">
            <template v-slot="scope">
              <img :src="img_url_pre(scope.row.commodity.pictures[0])" class="commodity-img" @dragstart.prevent alt="商品图片"
                style="border-radius: 5px; height: 85px; width: 85px;" />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="center">
            <template v-slot="scope">
              {{ scope.row.commodity.commodityName }}
            </template>
          </el-table-column>
          <el-table-column label="商品单价 / 元" align="center">
            <template v-slot="scope">
              {{ scope.row.commodity.price }}
            </template>
          </el-table-column>
          <el-table-column label="购买数量" prop="commodityNum" align="center" />
          <el-table-column label="商品总额 / 元" align="center">
            <template v-slot="scope">
              {{ (scope.row.commodityNum * scope.row.commodity.price).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 金额相关 -->
        <div class="total">
          <font-awesome-icon :icon="['fas', 'wallet']" />
          商品总价：￥
          <span class="amount">{{ item.originSum.toFixed(2) }}</span>
        </div>

        <!-- 收货信息 -->
        <div class="address-info" v-if="addressList.length > index">
          <p class="address-info-title">
            <font-awesome-icon :icon="['fas', 'location-dot']" />
            收货信息：
          </p>
          <el-card shadow="hover" style="margin-bottom: 5px; margin-top: 5px;">
            <!-- 信息展示 -->
            <div class="name-phone">
              <span class="name">{{ addressList[index].name }}</span>
              <span class="phone-number">{{ addressList[index].phoneNumber }}</span>
              <el-tag class="tag" size="small">{{ addressList[index].tag }}</el-tag>
            </div>
            <div class="addr">
              <span>{{ addressList[index].province }}</span>&emsp13;
              <span>{{ addressList[index].city }}</span>&emsp13;
              <span>{{ addressList[index].district }}</span>&emsp13;
              <span>{{ addressList[index].detail }}</span>
            </div>
          </el-card>
        </div>

        <!-- 订单备注 -->
        <div class="moreinfo">
          <p class="moreinfo-title">
            <font-awesome-icon :icon="['fas', 'clipboard']" />
            订单备注：
          </p>
          <el-input readonly v-model="item.moreInfo"></el-input>
        </div>

        <div class="order-id">
          订单编号：<span class="light-font">{{ item.orderId }}</span>
        </div>

        <div class="bill-id" v-if="item.status !== 0 && item.status !== 4">
          流水编号：<span class="light-font">{{ item.billId }}</span>
        </div>

        <!-- 订单相关的时间 -->
        <div class="time">
          创建时间：<span class="light-font">{{ item.createTime }}</span>
        </div>
        <div class="time" v-if="item.status !== 0 && item.status !== 4">
          付款时间：<span class="light-font">{{ item.payTime }}</span>
        </div>
        <div class="time" v-if="item.status === 3 || item.status === 2">
          发货时间：<span class="light-font">{{ item.deliveryTime }}</span>
        </div>
        <div class="time" v-if="item.status === 3">
          成交时间：<span class="light-font">{{ item.takeTime }}</span>
        </div>
      </div>
    </div>

    <div class="sum">
      <div class="activity">
        <font-awesome-icon :icon="['fas', 'fire']" />
        本次支付享受活动：
        <el-table :data="activityList" style="margin-top: 20px;">
          <el-table-column prop="activityId" label="活动ID"></el-table-column>
          <el-table-column prop="activityName" label="活动名称"></el-table-column>
          <el-table-column prop="startTime" label="活动开始时间"></el-table-column>
          <el-table-column prop="endTime" label="活动结束时间"></el-table-column>
          <el-table-column label="优惠力度">
            <template v-slot="scope">
              满
              <span style="font-size: 18px; color: #2e64c2;">{{ scope.row.reach.toFixed(2) }}</span>
              立减
              <span style="font-size: 18px; color: #2e64c2;">{{ scope.row.reduce.toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pay">
        <div>
          <font-awesome-icon :icon="['fas', 'credit-card']" />
          需支付金额：￥<span style="font-size: 32px; color: #ff3e28;">{{ totalAmount.toFixed(2) }}</span>
        </div>
        <div>
          <el-button type="success" plain round @click="payOrders" :loading="loading">支付订单</el-button>
          <el-button type="info" plain style="margin-left: 10px;" round @click="notPay">暂不支付</el-button>
        </div>
      </div>
    </div>
  </div>

  <el-dialog v-model="dialogVisible" width="30%" align-center>
    <el-result v-if="paySuccess" icon="success" title="支付成功" sub-title="本次订单已经支付">
      <template #extra>
        {{ Second }}秒后前往用户中心/待发货订单
      </template>
    </el-result>
    <el-result v-else icon="error" title="支付失败" sub-title="本次订单未能成功支付">
      <template #extra>
        {{ Second }}秒后前往用户中心/待支付订单
      </template>
    </el-result>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue';
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import img_url_pre from '../../../utils/img_url_filter';

const { proxy } = getCurrentInstance();
const router = useRouter();
const store = useStore();
const addressList = ref([]);
const loading = ref(false);
const commodityInfoList = ref([]);
const activityList = ref([]);
const totalAmount = ref(0.0);
const dialogVisible = ref(false);
const Second = ref(0.0);
const paySuccess = ref(false);

/**
 * 获取所有订单对应的收货地址
 */
const getAllOrderAddress = async () => {
  for (let i = 0; i < store.state.order.orderList.length; ++i) {
    let order = store.state.order.orderList[i];
    let ret = await proxy.$api.address.getAddress(order.addressId);
    addressList.value.push(ret.data);
  }
}

/**
 * 预览订单结算情况
 */
const calculate = async () => {
  store.state.order.orderList.forEach(order => {
    order.orderItemList.forEach(orderItem => {
      commodityInfoList.value.push({
        "storeId": orderItem.commodity.storeId,
        "commodityId": orderItem.commodity.commodityId,
        "commodityNum": orderItem.commodityNum
      })
    })
  });

  let ret = await proxy.$api.order.orderPreview({
    commodityInfoList: commodityInfoList.value,
  });
  if (ret.status === 200) {
    activityList.value = ret.data.activityList;
    totalAmount.value = ret.data.total;
  }
}

/**
 * 开始倒计时，解释后进行路由跳转
 */
const getSecond = () => {
  Second.value = 3;
  let interval = window.setInterval(function () {
    --Second.value
    if (Second.value === 0) {
      window.clearInterval(interval)

      // 滚动到顶部
      if (store.state.MallMainScrollBarRef) {
        store.state.MallMainScrollBarRef.setScrollTop(0);
      }

      if (paySuccess.value) {
        router.push('/mall/user_center/order/send');
      } else {
        router.push('/mall/user_center/order/pay');
      }
    }
  }, 1000)
}

/**
 * 支付订单
 */
const payOrders = async () => {
  loading.value = true;

  let orderIdList = [];
  store.state.order.orderList.forEach(order => orderIdList.push(order.orderId));
  let ret = await proxy.$api.order.payOrders({ orderIdList: orderIdList });
  if (ret.status === 200) {
    paySuccess.value = true;
  } else {
    paySuccess.value = false;
  }

  dialogVisible.value = true;
  // 开始倒计时
  getSecond();
}

/**
 * 暂不支付订单，前往用户中心待支付订单
 */
const notPay = async () => {
  // 滚动到顶部
  if (store.state.MallMainScrollBarRef) {
    store.state.MallMainScrollBarRef.setScrollTop(0);
  }
  router.push('/mall/user_center/order/pay');
}

onMounted(async () => {
  loading.value = true;
  await getAllOrderAddress();
  await calculate();
  loading.value = false;
})
</script>

<style lang="less" scoped>
.pay-card {
  background-color: white;
  width: 73%;
  margin: 20px auto 50px auto;
  padding: 20px 40px 20px 40px;
  border-radius: 20px;

  .title {
    font-size: 23px;
    margin-top: 5px;
    font-weight: 600;
  }

  .el-divider {
    border-top: 2px solid rgba(170, 165, 165, 0.651);
  }

  .expand-row {
    width: 94%;
    margin: 0 auto 0 auto;
    padding: 15px 20px 10px 20px;
    // background: red;

    .title {
      font-size: 18px;
      margin-bottom: 15px;
      color: black;
    }

    .total {
      font-size: 15px;
      margin-top: 10px;
      line-height: 35px;

      .amount {
        font-size: 25px;
        color: #ff3e28;
      }
    }

    .address-info {
      .address-info-title {
        font-size: 15px;
        line-height: 35px;
      }

      .name-phone {
        display: flex;
        align-items: center;

        .name {
          font-size: 16px;
        }

        .phone-number {
          font-size: 15px;
          margin-left: 10px;
        }

        .tag {
          margin-left: 10px;
        }
      }

      .addr {
        margin-top: 15px;
        font-size: 15px;
        color: rgb(147, 150, 152);
        line-height: 23px;
      }
    }

    .moreinfo {
      margin-top: 15px;

      .moreinfo-title {
        font-size: 15px;
        line-height: 35px;
        margin-bottom: 5px;
      }
    }

    .order-id {
      font-size: 15px;
      margin-top: 14px;
      line-height: 35px;

      .light-font {
        color: #989898;
      }
    }

    .bill-id {
      font-size: 15px;
      margin-top: 7px;
      line-height: 35px;

      .light-font {
        color: #989898;
      }
    }

    .time {
      font-size: 15px;
      margin-top: 7px;
      line-height: 35px;

      .light-font {
        color: #989898;
      }
    }
  }

  .sum {
    margin-top: 20px;

    .activity {
      margin-bottom: 50px;
    }

    .pay {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
}
</style>